# -*- coding: utf-8 -*-

import pymysql
from sshtunnel import SSHTunnelForwarder

import pymysql.cursors

class db_con:
	def __init__(self, db_host, db_name, db_port, db_user, db_pwd):
		self.db_host = db_host
		self.db_name = db_name
		self.db_port = db_port
		self.db_user = db_user
		self.db_pwd = db_pwd

		self.db_connect()

	def db_connect(self):
		self.db = pymysql.connect(
			host = self.db_host,
			port = self.db_port,
			user = self.db_user,
			passwd = self.db_pwd,
			db = self.db_name,
			charset = "utf8",
			cursorclass = pymysql.cursors.DictCursor
		)

	def getCollect(self, sql):

		cursor = self.db.cursor()

		try:
			cursor.execute(sql)
			data = cursor.fetchall()
			self.db.commit()
		except Exception as e:
			self.db.rollback()
			raise e

		collect = []
		for result in data:
			collect.append(result)
		cursor.close

		return collect

	def insert(self, sql):
		cursor = self.db.cursor()
		try:
			cursor.execute(sql)
			self.db.commit()
			mes = 1
		except Exception as e:
			print(e)
			self.db.rollback()
			mes = 0
		
		return mes

	def close(self):
		self.db.close

if __name__ == '__main__':
	sql = 'select * from financial_news_title limit 2'
	mysql = db_con('192.168.1.51','financial',3306,'root','123456')
	print(mysql.getCollect(sql))